export default {
	namespaced: true,
	state: () => ({
		cart: JSON.parse(uni.getStorageSync('cart') || '[]')
	}),
	mutations: {
		updateAllGoodsState(state, newState) {
			state.cart.forEach(item => item.goods_state = newState)
			this.commit('m_cart/saveCartToStorage')
		},
		removeGoodsById(state, goods_id) {
			state.cart = state.cart.filter(temp => temp.goods_id != goods_id);
			this.commit('m_cart/saveCartToStorage')
		},
		updateGoodsCount(state, goods) {
			const findGoods = state.cart.find(temp => temp.goods_id == goods.goods_id)
			if (findGoods) {
				findGoods.goods_count = goods.goods_count
				this.commit('m_cart/saveCartToStorage')
			}
		},
		updateGoodsState(state, goods) {
			const findGoods = state.cart.find(temp => temp.goods_id == goods.goods_id)
			if (findGoods) {
				findGoods.goods_state = goods.goods_state
				this.commit('m_cart/saveCartToStorage')
			}
		},
		addToCart(state, goods) {
			const findGoods = state.cart.find(temp => temp.goods_id == goods.goods_id)
			if (!findGoods) {
				state.cart.push(goods)
			} else {
				findGoods.goods_count++;
			}
			this.commit('m_cart/saveCartToStorage')
		},
		saveCartToStorage(state) {
			uni.setStorageSync('cart', JSON.stringify(state.cart))
		}
	},
	getters: {
		checkedGoodsAmount(state){
			return state.cart.filter(temp => temp.goods_state).reduce((total,item) => item.goods_price * item.goods_count, 0).toFixed(2);
		},
		total(state) {
			let count = 0;
			state.cart.forEach(temp => {
				count += temp.goods_count;
			})
			return count;
		},
		checkedCount(state) {
			return state.cart.filter(temp => temp.goods_state).reduce((total, item) => total += item.goods_count, 0)
		}
	}
}
